package data;

import dao.SQLiteConnection;
import gui.LoginWin;
import data.admin.MS;
import data.reader.ReaderSelect;
import javax.swing.*;
import java.sql.*;
import static utils.AESEncryption.encrypt;

public class Login extends LoginWin {

    private String username;

    public Login() {
        getLoginButton1().addActionListener(e -> {
            username=getAdmin().getText();
            String password = String.valueOf(getPasswordField().getPassword());
            // 密码加密
            try {
                password=encrypt(password);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            String sql;
            //读者
            if(getR1().isSelected()){
                sql="SELECT * FROM Reader WHERE rid=? AND rpassword=?";
                if (match(username,password,sql) == 1) {
                    // 登录成功
                    System.out.println("读者"+username+"登录成功！");
                    //关闭登录窗口LoginWin
                    dispose();
                    //打开借阅界面
                    new ReaderSelect(username);
                } else {
                    // 登录失败
                    JOptionPane.showMessageDialog(this,"账号或密码错误！");
                }
            }
            //管理员
            if(getR2().isSelected()){
                sql="SELECT * FROM Admin WHERE aid=? AND apassword=?";
                if (match(username,password,sql) == 1) {
                    // 登录成功
                    System.out.println("管理员"+username+"登录成功！");
                    //关闭登录窗口LoginWin
                    dispose();
                    //打开借阅界面
                    new MS();
                } else {
                    // 登录失败
                    JOptionPane.showMessageDialog(this,"账号或密码错误！");
                }
            }

        });
    }

    //登录匹配
    private int match(String username,String password,String sql) {
        //连接数据库
        SQLiteConnection dbConnection = new SQLiteConnection();
        dbConnection.Connect_SQLite();
        //获取数据库信息
        Connection conn = dbConnection.getConnection();
        //验证管理员登录验证
        PreparedStatement stmt;
        ResultSet rs;
        try {
            // 查询USERS表中是否有匹配的用户名和密码
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();
            if (rs.next()) {
                return 1;
            } else {
                return 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbConnection.closeConnection();
        }
        return -1;
    }

}

